﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using sorochinska_kl.Models;
using WebMatrix.WebData;

namespace sorochinska_kl.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/

        [Authorize(Roles = "Admin")]
        public ActionResult Index()
        {
            return View();
        }

        private UsersContext db = new UsersContext();

        [Authorize(Roles = "Admin")]
        public ActionResult AddUserToRole()
        {
            ViewBag.UserID = new SelectList(db.UserProfiles, "UserId", "UserName");
            var roles = db.UserRoles;
            ViewBag.RoleID = new SelectList(db.UserRoles, "RoleId", "RoleName");
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        public ActionResult AddUserToRole(AddUserToRole model)
        {

            Roles.AddUserToRole(db.UserProfiles.Find(model.UserId).UserName, db.UserRoles.Find(model.RoleId).RoleName);

            ViewBag.UserID = new SelectList(db.UserProfiles, "UserId", "UserName");
            ViewBag.RoleID = new SelectList(db.UserRoles, "RoleId", "RoleName");

            return RedirectToAction("Index", "Home");
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Users()
        {
            return View(db.UserProfiles.ToList());
        }

        [Authorize(Roles = "Admin")]
        public ActionResult CreateUser()
        {
            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Admin")]
        public ActionResult CreateUser(UserProfile model)
        {
            if (ModelState.IsValid)
            {
                WebSecurity.CreateUserAndAccount(model.UserName, "123456");
                return RedirectToAction("Index");
            }

            return View(model);
        }
    }
}
